<?php

require_once("UserStates.php");

class ApplicationSession {

	private $db;
	
	function __construct() {
		session_start();
		$this->db = new MySQLDB(DB_HOST, DB_USER, DB_PW, DB_NAME);

	}
	function __destruct(){
		$this->db->disconnect();	
	}
	
	public function getDB(){
		return $this->db;
	}
	
	public function endSession(){
		session_regenerate_id();
		session_destroy(); 
	}
	
	public function login($user, $password){
		
		$result = $this->db->executeQuery("select name, password from user where name = '".$user."' and password = '".md5($password)."'");
		
		if(mysql_num_rows($result) == 1){	
			$isActive = mysql_fetch_row($this->db->executeQuery("select state from user where name = '".$user."'"));
			if($isActive[0] == BANNED){
				return "{ \"success\": false, \"error\" : \"You are banned!\" }";
			}else {
				$this->db->executeQuery("update user set state = ".ONLINE." where name = '".$user."'");
				$_SESSION['userName'] = $user;
				$_SESSION['isLogin'] = true;
				if($user == "0x1d"){
					$_SESSION['isAdmin'] = true;
				}
				return "{ \"success\": true }";
			}		
		} else {
			$_SESSION['isLogin'] = false;
			return "{ \"success\": false, \"error\" : \"Wrong username or password\" }";
		}
		
	}
	
	public function register($user, $password){
		$exists = $this->db->executeQuery("select name from user where name = '".$user."'");
		if(mysql_num_rows($exists) > 0){	
			return "{ \"success\": false, \"error\" : \"Username already exists\" }";
		} else {
			$this->db->executeQuery("insert into user(name, password) values('".$user."','".md5($password)."')");
			return "{ \"success\": true }";	
		}
		
	}
	
	public function banUser($user){
		if($_SESSION['isAdmin']){
			$this->db->executeQuery("update user set state = ".BANNED." where name = '".$user."'");
			return "{msg : 'Ext.Msg.alert(\"Ban\",\"User ".$user." has been banned\")'}";
		}
	}
	
	public function unbanUser($user){
		if($_SESSION['isAdmin']){
			$this->db->executeQuery("update user set state = ".OFFLINE." where name = '".$user."'");
			return "{msg : 'Ext.Msg.alert(\"Unban\",\"User ".$user." has been unbanned\")'}";
		}
	}
	
	public function logout(){
		$this->db->executeQuery("update user set state = ".OFFLINE." where state < ".BANNED." and name = '".$_SESSION['userName']."'");
		$this->endSession();
	}
	
	public function changeLoginData($user, $password){
		$this->db->executeQuery("update user set name = '".$user."', password = '".md5($password)."' where name = '".$_SESSION['userName']."'");
		$_SESSION['userName'] = $user;
	}

	public function updateLastContact(){
		$_SESSION['lastContact'] = date('Y-m-d H:i:s', time());
	}
		
	public function getCurrentUser(){
		return $_SESSION['userName'];
	}
	
	public function getLastContact(){
		if(isset($_SESSION['lastContact'])){
			return $_SESSION['lastContact'];
		} else {
			return date('Y-m-d H:i:s', time());
		}
		
	}
}

?>